<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../../lib/layui-v2.5.6/layui/css/layui.css">
</head>
<style> 
.layui-form-label{
    padding-left: 0px;
    width: 60px;
}
.layui-form-radio {
    margin-right: 0px;
    padding-right: 5px;
}


</style>
<body>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md7" style="height: 93px;">
            <div class="layui-card">
              <div class="layui-card-body  " style="height: 58px;">
               
                <form id="form" class="layui-form" action="">                    
                    <div class="layui-form-item">
                      <label class="layui-form-label">车辆选择:</label>
                      <div class="layui-input-inline">
                        <select id="carSel" lay-filter="carSel" name="quiz1">
                        </select>
                      </div>

                      <div class="layui-input-inline" >
                          <input type="text" class="layui-input" autocomplete="off" id="startDateTime"/> 
                      </div>
                      
                      <div class="layui-input-inline" style="width: 10px;padding-top: 5px;">
                        <span>--</span>
                      </div>
                    
                      <div class="layui-input-inline">
                        <input type="text" class="layui-input" autocomplete="off" id="endDateTime"/>
                      </div>
                      <div class="layui-input-inline" style="margin-left: 20px;">
                        <button type="button" id="getTrackBtn" class="layui-btn">查找</button>
                      </div>
                    </div>                  
                </form>

              </div>
            </div>
          </div>
          <div class="layui-col-md5">
            <div class="layui-card">
              <div  class="layui-card-body ">
                <form id="form" class="layui-form" action=""> 


                    <div class="layui-form-item">

                        <div class="layui-inline">
                            <label class="layui-form-label">图标尺寸</label>
                            <div class="layui-input-inline" style="width: 160px;">
                                <input type="radio" lay-filter="iconRadio" name="iconSize" value="Big" title="大" checked>
                                <input type="radio" lay-filter="iconRadio" name="iconSize" value="Middle" title="中" >
                                <input type="radio" lay-filter="iconRadio" name="iconSize" value="Little" title="小" >
                            </div>
                        </div>
                   
                       <!-- <div class="layui-inline"> 
                            <label class="layui-form-label">跟踪车辆</label>
                            <div class="layui-input-inline" style="width: 60px;">
                                <input type="checkbox" lay-filter="followCar" lay-text="开启|关闭" checked name="switch" lay-skin="switch">
                            </div>
                        </div> -->

                        <!-- <div class="layui-inline"> 
                            <label class="layui-form-label">实时轨迹</label>
                            <div class="layui-input-inline" style="width: 60px;">
                                <input type="checkbox" lay-filter="trackCar" lay-text="开启|关闭"  name="switch" lay-skin="switch">
                            </div>
                        </div> -->
                    </div>

                </form>
              </div>
            </div>
          </div>
         
          <div class="layui-col-md12">
            <div class="layui-card">
              <div class="layui-card-body" style="height: 660px;">
                 <div id="mapDiv" style="height: 100%;"></div>
              </div>
            </div>
          </div>
          
        </div>
      </div>
</body>
<script src='../../lib/js/turf.min.js'></script>
<script src="../../lib/layui-v2.5.6/layui/layui.js"></script>
<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=YS7BZ-KO2HP-GYBDJ-LKSJ7-QDMKE-WVBG7"></script>

<script>


layui.use(['form', 'jquery','layedit', 'laydate','element'], function(){
    form = layui.form;
    $ = layui.$;
    var laydate = layui.laydate;

    laydate.render({
        elem: '#startDateTime' //指定元素
        ,type: 'datetime'
        ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
        ,btns: ['now', 'confirm']
    });
    laydate.render({
        elem: '#endDateTime' //指定元素
        ,type: 'datetime'
        ,value:new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1)
        ,btns: ['now', 'confirm']
    });
    var timerArr = [];
    var pointLinArr = [];
    var pointLinTimeArr = [];

    var map,markersArray = [];
    var markersTimeArray = [];
    var latitude = "";
    var longitude = "";

    var carId = "";
    var startMarkerIcon = "";
    var endMarkerIcon = "";

    var isFollowCar = true;
    var isTrackCar = false;
    var polyline = "";      
    var marker ="";
    var polylineArr = [];
    var turfPointArr = [];
    var markesToInfoJsonArr = [];

    $(function(){
        getCarList();
        initMap();
        carId = $("#carSel").val();
        getMakerIcon("Big")
        //makePoint();
        //监听切换车辆
        // form.on('select(carSel)', function(data){
        //     pointLinArr = [];
        //     carId = data.value;
        //     //移除定时器
        //     for(var k = 0 ; k < timerArr.length; k++){
        //         clearInterval(timerArr[k]);
        //     }
        //     makePoint();
        // }); 
        //监听图标尺寸
        form.on('radio(iconRadio)', function(data){
            getMakerIcon(data.value);
            console.log(markersArray)
            for(var i = 0; i < markersArray.length;i++){
                if(i%2 == 0){
                    markersArray[i].setIcon(startMarkerIcon)
                }else{
                    markersArray[i].setIcon(endMarkerIcon)
                }
                
            }
        });    
        //监听是否跟踪车辆
        form.on('switch(followCar)', function(data){
            isFollowCar = data.elem.checked
        });
        // //监听是否开启轨迹线
        // form.on('switch(trackCar)', function(data){
        //     pointLinArr = [];
        //     isTrackCar = data.elem.checked
        // });
    })


    $("#getTrackBtn").click(function(){
        //清空路线数组
        pointLinArr = [];

        //清除地图上已经存在的轨迹线
        for(var i = 0; i < polylineArr.length;i++){
            polylineArr[i].setVisible(true);
            polylineArr[i].setMap(null);
        }
        polylineArr = [];

        //清除地图上的标记点
        for(var i = 0; i < markersArray.length;i++){
            markersArray[i].setVisible(true);
            markersArray[i].setMap(null);
        }
        markersArray = [];

        for(var i = 0; i < markesToInfoJsonArr.length;i++){
            console.log( markesToInfoJsonArr[i].info)
            markesToInfoJsonArr[i].info.close();
        }



        markersTimeArray=[];

        turfPointArr = [];
        markesToInfoJsonArr = [];

        //获取所有路线
        getTrack($("#carSel").val(),$("#startDateTime").val(),$("#endDateTime").val())
      
        //遍历路线集合,对每条路线进行绘线
        for(var i = 0 ; i < pointLinArr.length;i++){
            //获取本条路线的起点
            var startPoint = pointLinArr[i][0]
            //生成本条路线的起点
            var startMarker = new qq.maps.Marker({
                            position: startPoint,
                            map: map,
                            icon:startMarkerIcon
                        });
            markersArray.push(startMarker)
            markersTimeArray.push(pointLinTimeArr[i][0])
            //将本标记点存入该数组,为以后做中心点计算做准备
            turfPointArr.push(turf.point([startMarker.getPosition().lat,startMarker.getPosition().lng]))        
            
            //获取本条路线的终点
            var endPoint = pointLinArr[i][pointLinArr[i].length-1]
            //生成本条路线的终点
            var endMarker = new qq.maps.Marker({
                        position: endPoint,
                        map: map,
                        icon:endMarkerIcon
                    });
            markersArray.push(endMarker)
            markersTimeArray.push(pointLinTimeArr[i][pointLinTimeArr[i].length-1])
            //将本标记点存入该数组,为以后做中心点计算做准备
            turfPointArr.push(turf.point([endMarker.getPosition().lat,endMarker.getPosition().lng]))
            
            //将本条路线绘制出来
            polyline = new qq.maps.Polyline({
                path: pointLinArr[i],
                strokeColor: '#FF0000',
                strokeWeight: 6,
                map
            })
            polylineArr.push(polyline)
        }

        //根据所有轨迹的起点和终点重新设置整体地图的中心点和放大倍数
        if(turfPointArr.length> 0){
            var features = turf.featureCollection(turfPointArr);
            var center = turf.center(features);
            map.panTo(new qq.maps.LatLng(center.geometry.coordinates[0], center.geometry.coordinates[1]))
            map.zoomTo(10);
      
        }
                
        for(var i = 0; i < markersArray.length;i++){
            var markesToInfoJson = {};
            var mark = markersArray[i]
            var info = new qq.maps.InfoWindow({
                map: map
            });
            markesToInfoJson["mark"] = mark;
            markesToInfoJson["info"] = info;
            markesToInfoJson["time"] = markersTimeArray[i];
            markesToInfoJsonArr.push(markesToInfoJson);
        }

        for(var i = 0; i < markesToInfoJsonArr.length;i++){


            qq.maps.event.addListener(markesToInfoJsonArr[i].mark, 'click', function(e) {
              
                for(var i = 0; i < markesToInfoJsonArr.length;i++){
                    if(e.latLng.lat == markesToInfoJsonArr[i].mark.getPosition().lat && 
                    e.latLng.lng ==  markesToInfoJsonArr[i].mark.getPosition().lng){
                        var info = markesToInfoJsonArr[i].info;
                        info.open(); 
                        info.setContent('<div style="text-align:left;white-space:nowrap;'+
                        'margin:5px;">'+dateToString(new Date(markersTimeArray[i]))+'</div>');
                        info.setPosition(markesToInfoJsonArr[i].mark.getPosition());

                    }
                }


                 
            });




        }








    });


    form.on('switch(followCar)', function(data){
        isFollowCar = data.elem.checked
    });

    //地图初始化
    function initMap() {
        var myLatlng = new qq.maps.LatLng(41.8,123.38);
        var myOptions = {
            zoom: 10,
            center: myLatlng,
            mapTypeId: qq.maps.MapTypeId.ROADMAP
        }
        map = new qq.maps.Map(document.getElementById("mapDiv"), myOptions);

    }

    //获取车辆列表
    function getCarList(){
        $.ajax({
            url:"https://device-dev.horus.net.cn/api/vehicle/getVehicle",
            data:{
                "Authorization":"eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ"
            },
            type:"get",
            async:false,
            success:function(res){
                carList = res.content;
                var opt = "";
                for(var i = 0; i < carList.length;i++){
                    opt += "<option value='" + carList[i].id +"'";
                    if(i == 0){
                        opt += "selected "
                    }
                    opt +=" >"+ carList[i].number +"</option>";
                }
                
                $("#carSel").html(opt);
                form.render('select')                   
            }
        })
    }

     //获取历史轨迹
    function getTrack(carId,startDateTime,endDateTime){
        $.ajax({
            url:"https://device-dev.horus.net.cn/api/vehicle/getPosition",
            data:{
                "Authorization":"eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ",
                "vid":carId,
                "begin":startDateTime,
                "end":endDateTime
            },
            type:"get",
            async:false,
            success:function(res){
                var track = res.content;  
                var newPath = [];
                var newPathTime= [];

                for(var i = 0 ; i < track.length; i++){
                    var newLaLng = new qq.maps.LatLng(track[i].latitude,track[i].longitude);
                    newPath.push(newLaLng);
                    newPathTime.push(track[i].timestamp);

                    if(i == track.length-1){
                        pointLinArr.push(newPath);
                        pointLinTimeArr.push(newPathTime);
                        break;
                    }
                    //比较两个点之间的时间差,大于规定时间则重新生成一段轨迹
                    if((track[i+1].timestamp-track[i].timestamp) > (300*1000)){
                        pointLinArr.push(newPath);
                        pointLinTimeArr.push(newPathTime);
                        newPath = [];
                        newPathTime= [];
                    }
                }

            }
        })

    }




    //根据车辆id获取最后坐标点
    function getLastLocationByCarId(carId){
        $.ajax({
            url:"https://device-dev.horus.net.cn/api/vehicle/getLastPosition",
            data:{
                "Authorization":"eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjIsImFwcElkIjoiaG9ydXMiLCJyb2xlTGlzdFN0ciI6IiIsImV4cCI6NDcxNzk2NjgzNn0.r1G1EaNV2dPraRooct5TtsQ8gSIRcR7kL49xQzpL8BtPWeZOGgaTgO8xZS4xzWKY9rppuZV0eko84Jb2RAmPNQ",
                "vid":carId
            },
            type:"get",
            async:false,
            success:function(res){
                latitude = res.content.latitude;
                longitude = res.content.longitude;
            }
        })
    }




    //在地图上描绘坐标点
    function makePoint(){
        var j = 0.0000;
        var timer = setInterval( 
                function(){
                    //获取最后坐标点
                    getLastLocationByCarId(carId);
                   
                    //获取新的坐标点并加载到地图上
                    var lastLocation = new qq.maps.LatLng(latitude + 0.0001*j,longitude + 0.0001*j);
                    map.center = lastLocation;

                    if(marker != "" && marker != undefined){
                        marker.setPosition(lastLocation) //移动坐标点
                    }else{
                        marker = new qq.maps.Marker({
                            position: lastLocation,
                            map: map,
                            icon:markerIcon
                        });
                    }
                    
                    //地图重置中心点
                    if(isFollowCar){
                        map.panTo(lastLocation);
                    }

                    if(isTrackCar){
                        pointLinArr.push(lastLocation);
                    }
                    
                    //这样做是为了轨迹线是实时的, 有且只有一根轨迹线
                    if(polyline != "" && polyline != undefined){
                        polyline.setPath(pointLinArr)

                    }else{
                        polyline = new qq.maps.Polyline({
                            path: pointLinArr,
                            strokeColor: '#FF0000',
                            strokeWeight: 3,
                            map
                        });
                    }
                    

                    markersArray.push(marker);
                    j++
                }, 
            100);
        timerArr.push(timer)
    }

    //车辆图标
    function getMakerIcon(iconName){

        if(iconName == "Big"){
            var size = new qq.maps.Size(64,64);//图片大小
            var origin = new qq.maps.Point(0, 0);//
            var anchor = new qq.maps.Point(32, 64);//锚点坐标x,y
            iconName 
        }else if(iconName == "Middle"){
            var size = new qq.maps.Size(48,48);//图片大小
            var origin = new qq.maps.Point(0, 0);//
            var anchor = new qq.maps.Point(24, 48);//锚点坐标x,y
        }else if(iconName == "Little"){
            var size = new qq.maps.Size(32,32);//图片大小
            var origin = new qq.maps.Point(0, 0);//
            var anchor = new qq.maps.Point(16, 32);//锚点坐标x,y
        }


        startMarkerIcon = new qq.maps.MarkerImage(
                "../../lib/image/startPoint"+iconName+".png",
                size,
                origin,
                anchor
            );
        endMarkerIcon = new qq.maps.MarkerImage(
            "../../lib/image/endPoint"+iconName+".png",
            size,
            origin,
            anchor
        );

        
    }


    function dateToString(date){ 
        var year = date.getFullYear(); 
        var month =(date.getMonth() + 1).toString(); 
        var day = (date.getDate()).toString();  
        var hour = (date.getHours()).toString();
        var min = (date.getMinutes()).toString();
        var sec = (date.getSeconds()).toString();
        if (month.length == 1) { 
            month = "0" + month; 
        } 
        if (day.length == 1) { 
            day = "0" + day; 
        }
        var dateTime = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
        return dateTime; 
    }

  

})


</script>
</html>